package com.example.satoken.config.saInterceptor;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.example.satoken.common.ResponseCode;
import com.example.satoken.common.exception.BaseException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
public class SaTokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String token = request.getHeader("Authorization");
        StpUtil.getTokenTimeout();
        // 未登录 token校验
        if (StrUtil.isBlank(token)
                ||
                // token 过期
                Objects.isNull(StpUtil.getTokenInfo()) || StrUtil.isBlank(StpUtil.getTokenInfo().getTokenValue())
                ||
                // token 不匹配
                !token.equalsIgnoreCase(StpUtil.getTokenInfo().getTokenValue())) {
            // 登录验证未通过，进行拦截处理
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException(401, "【用户未登录】 或 【登录过期】!");
        }
        // 登录不是活跃会话，相当于登录失效，同账号被挤。
        if (!StpUtil.isLogin()) {
            throw new BaseException(ResponseCode.LOG_OUT.getCode(), ResponseCode.LOG_OUT.getMsg());
        }
        return true;
    }
}